# -*- coding: utf-8 -*-
"""
# --------------------------------------------------------
# @Author : Pan
# @E-mail : 
# @Date   : 2025-10-29 18:12:00
# @Brief  : USB摄像头实时分析示例
# --------------------------------------------------------
"""
import sys
import os
import time
from PIL import Image
import numpy as np
from pybaseutils.base import list_queue
from pybaseutils import image_utils, file_utils
from pybaseutils.cvutils import video_utils


class VideoCamera(object):
    def __init__(self, ):
        pass

    def chat_video(self, question: str, images: list = [], enable_thinking=False, stream=True):
        for frame in images:
            image_utils.cv_show_image("image", frame, delay=10)
        # 构建消息格式
        result = {"role": "assistant", "content": ["output"]}
        return result

    def camera_example(self, question, video, freq=2, winsize=6, overlap=0.5, enable_thinking=False, stream=False):
        """
        实时分析功能，从视频中提取帧进行分析
        :param question:
        :param video:
        :param freq:
        :param winsize:
        :param overlap:
        :param enable_thinking:
        :param stream:
        :return:
        """
        from pybaseutils.cvutils import video_utils
        from pybaseutils.base import list_queue
        w, h, nums, fps = video_utils.get_video_info(video)
        video_cap = video_utils.video_iterator(video, freq=freq, vis=False)
        queue = list_queue.Queue(maxsize=100)
        for data_info in video_cap:
            frame = data_info["frame"]
            count = data_info["count"]
            frame = frame[:, :, ::-1]  # BGR to RGB
            time = round(data_info["count"] / fps, 3)
            info = {"count": count, "time": time, "frame": frame, "fps": fps, "w": w, "h": h}
            queue.put(info, block=False)
            while queue.qsize() > winsize:
                data_list = queue.get_window(winsize=winsize, overlap=overlap) # 提取窗口数据
                times_ = [data_list[0]['time'], data_list[-1]['time']]
                offset = [info['count'] for info in data_list]
                images = [data['frame'] for data in data_list]
                result = self.chat_video(question, images=images, enable_thinking=enable_thinking, stream=stream)
                print("分析结果: time={:20s},offset={}, result={}".format(str(times_), offset, result))
        return None


if __name__ == '__main__':
    image_file = "../../data/image1.jpg"
    video_file = "../../data/video2.mp4"
    question = "视频中的人在做什么?"
    vc = VideoCamera()
    vc.camera_example(question, video_file)
